#include "roster.h"
#include "connecttocoredialog.h"

Roster::Roster(QObject *parent) :
    QObject(parent)
{
}

/**
* @brief close the dialog and NULL it
*/
void Roster::closeCtcDialog()
{
  // enable/disable menubuttons
  this->form->actionConnect_to_Core->setEnabled(false);
  this->form->actionDisconnect_from_Core->setEnabled(true);

  // close the dialog and NULL it
  if(this->ctcdlg)
    this->ctcdlg->close();
  this->ctcdlg = NULL;
}

/**
* @brief show the connect to core dialog
*/
void Roster::showConnectToCoreDialog()
{
    this->ctcdlg = new ConnectToCoreDialog();


    /** Read accounts from filesystem */
    settings->beginGroup("accounts");
    QHash<QString,QHash<QString,QVariant> > accs;
    QStringList accounts = settings->childGroups();
    for (int i=0;i<accounts.length();i++)
    {
        settings->beginGroup(accounts.value(i));
        QHash<QString,QVariant> t;
        QStringList keys = settings->childKeys();
        for (int j=0;j<keys.length();j++)
        {
            t.insert(keys.value(j),settings->value(keys.value(j)));
        }
        accs.insert(accounts.value(i),t);
        this->ctcdlg->form->accountList->addItem(accounts.value(i));
        settings->endGroup();
    }
    settings->endGroup();
    if(this->ctcdlg->form->accountList->count() > 0)
      this->ctcdlg->form->accountList->item(0)->setSelected(true);


    connect(this->ctcdlg,SIGNAL(startConnect(QString,QString,QString,QString)),this,SLOT(secureConnect(QString,QString,QString,QString)));
    connect(this,SIGNAL(connected()),this,SLOT(closeCtcDialog()));
    connect(this,SIGNAL(connected()),this,SLOT(requestRosterEntries()));

    this->ctcdlg->show();
}
/**
* @brief get the chatWidget for a concrete buddy
* @returns a pointer to the ChatWidget corresponding to the given accid/jid pair.
*
* If it does not yet exist (== starting a fresh conversation)
* it is created.
*/
chatWidget* SslClient::getChatWidget(int accID,QString jid,QString name)
{
    // If there is a chatWidet already, we return it.
    // Otherwise, we return a new instance
    chatWidget *w = this->chatsWidgets.value(accID).value(jid,NULL);
    if (!w)
    {

        w = new chatWidget(accID,name,jid);
        QHash<QString,chatWidget*> t = this->chatsWidgets.value(accID);
        t.insert(jid,w);
        this->chatsWidgets.insert(accID,t);
        this->mainChatWindow->addDockWidget(Qt::TopDockWidgetArea,w);
        connect(w,SIGNAL(msgSend(int,QString,QString)),this,SLOT(msgSend(int,QString,QString)));
        connect(this,SIGNAL(buddyUpdate(QString,QString,QModelIndex)),w,SLOT(updateBuddy(QString,QString,QModelIndex)));
        connect(w,SIGNAL(stateChanged(int,QString,QString)),this,SLOT(stateChanged(int,QString,QString)));
        // only allow to be docked in the top dockarea
        w->setAllowedAreas(Qt::TopDockWidgetArea);
    }
    w->show();
    if(!w->isFloating())
      this->mainChatWindow->show();
    return w;
}
